package com.ruoyi.business.service.impl;

import com.ruoyi.business.domain.Order;
import com.ruoyi.business.domain.OrderItem;
import com.ruoyi.business.mapper.OrderItemMapper;
import com.ruoyi.business.mapper.OrderMapper;
import com.ruoyi.business.service.IOrderService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 微信小程序订单Service业务层处理
 */
@Service
public class OrderServiceImpl implements IOrderService {
    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private OrderItemMapper orderItemMapper;

    /**
     * 查询订单
     * 
     * @param orderId 订单ID
     * @return 订单
     */
    @Override
    public Order selectOrderById(Long orderId) {
        Order order = orderMapper.selectOrderById(orderId);
        if (order != null) {
            // 查询订单明细
            List<OrderItem> items = orderItemMapper.selectOrderItemsByOrderId(orderId);
            order.setItems(items);
        }
        return order;
    }

    /**
     * 查询订单列表
     * 
     * @param openid 微信用户openid
     * @param status 订单状态
     * @return 订单集合
     */
    @Override
    public List<Order> selectOrderList(String openid, String status) {
        Order order = new Order();
        order.setOpenid(openid);
        if (StringUtils.isNotEmpty(status)) {
            order.setStatus(status);
        }
        List<Order> orders = orderMapper.selectOrderList(order);
        
        // 查询每个订单的明细
        for (Order o : orders) {
            List<OrderItem> items = orderItemMapper.selectOrderItemsByOrderId(o.getOrderId());
            o.setItems(items);
        }
        
        return orders;
    }

    /**
     * 新增订单
     * 
     * @param order 订单
     * @return 结果
     */
    @Override
    @Transactional
    public int insertOrder(Order order) {
        try {
            // 生成订单号
            String orderNo = generateOrderNo();
            order.setOrderNo(orderNo);
            
            // 设置创建时间
            order.setCreateTime(DateUtils.getNowDate());
            order.setCreateBy(SecurityUtils.getUsername());
            order.setDelFlag("0");
            
            // 插入订单
            int rows = orderMapper.insertOrder(order);
            
            // 插入订单明细
            List<OrderItem> items = order.getItems();
            if (items != null && !items.isEmpty()) {
                for (OrderItem item : items) {
                    item.setOrderId(order.getOrderId());
                    item.setCreateTime(DateUtils.getNowDate());
                    item.setCreateBy(SecurityUtils.getUsername());
                    item.setDelFlag("0");
                    orderItemMapper.insertOrderItem(item);
                }
            }
            
            return rows;
        } catch (Exception e) {
            log.error("新增订单异常", e);
            throw e;
        }
    }

    /**
     * 修改订单
     * 
     * @param order 订单
     * @return 结果
     */
    @Override
    public int updateOrder(Order order) {
        order.setUpdateTime(DateUtils.getNowDate());
        order.setUpdateBy(SecurityUtils.getUsername());
        return orderMapper.updateOrder(order);
    }

    /**
     * 取消订单
     * 
     * @param orderId 订单ID
     * @return 结果
     */
    @Override
    @Transactional
    public int cancelOrder(Long orderId) {
        // 查询订单
        Order order = orderMapper.selectOrderById(orderId);
        if (order == null) {
            return 0;
        }
        
        // 判断订单状态是否可取消（只有待付款状态可取消）
        if (!"0".equals(order.getStatus())) {
            return 0;
        }
        
        // 更新订单状态为已取消
        Order updateOrder = new Order();
        updateOrder.setOrderId(orderId);
        updateOrder.setStatus("4"); // 已取消
        updateOrder.setCancelTime(DateUtils.getTime());
        updateOrder.setUpdateTime(DateUtils.getNowDate());
        updateOrder.setUpdateBy(SecurityUtils.getUsername());
        
        return orderMapper.updateOrder(updateOrder);
    }
    
    /**
     * 支付订单
     * 
     * @param orderId 订单ID
     * @return 结果
     */
    @Override
    @Transactional
    public int payOrder(Long orderId) {
        // 查询订单
        Order order = orderMapper.selectOrderById(orderId);
        if (order == null) {
            return 0;
        }
        
        // 判断订单状态是否可支付（只有待付款状态可支付）
        if (!"0".equals(order.getStatus())) {
            return 0;
        }
        
        // 模拟调用支付接口，此处省略实际支付逻辑
        
        // 更新订单状态为待发货
        Order updateOrder = new Order();
        updateOrder.setOrderId(orderId);
        updateOrder.setStatus("1"); // 待发货
        updateOrder.setPayTime(DateUtils.getTime());
        updateOrder.setUpdateTime(DateUtils.getNowDate());
        updateOrder.setUpdateBy(SecurityUtils.getUsername());
        
        return orderMapper.updateOrder(updateOrder);
    }
    
    /**
     * 申请退款
     * 
     * @param orderId 订单ID
     * @param reason 退款原因
     * @return 结果
     */
    @Override
    @Transactional
    public int refundOrder(Long orderId, String reason) {
        // 查询订单
        Order order = orderMapper.selectOrderById(orderId);
        if (order == null) {
            return 0;
        }
        
        // 判断订单状态是否可申请退款（已支付状态才可申请退款）
        if ("0".equals(order.getStatus()) || "4".equals(order.getStatus()) || "6".equals(order.getStatus())) {
            return 0;
        }
        
        // 更新订单状态为申请退款
        Order updateOrder = new Order();
        updateOrder.setOrderId(orderId);
        updateOrder.setStatus("5"); // 申请退款
        updateOrder.setRefundReason(reason);
        updateOrder.setUpdateTime(DateUtils.getNowDate());
        updateOrder.setUpdateBy(SecurityUtils.getUsername());
        
        return orderMapper.updateOrder(updateOrder);
    }
    
    /**
     * 确认收货
     * 
     * @param orderId 订单ID
     * @return 结果
     */
    @Override
    @Transactional
    public int confirmOrder(Long orderId) {
        // 查询订单
        Order order = orderMapper.selectOrderById(orderId);
        if (order == null) {
            return 0;
        }
        
        // 判断订单状态是否可确认收货（只有待收货状态可确认收货）
        if (!"2".equals(order.getStatus())) {
            return 0;
        }
        
        // 更新订单状态为已完成
        Order updateOrder = new Order();
        updateOrder.setOrderId(orderId);
        updateOrder.setStatus("3"); // 已完成
        updateOrder.setFinishTime(DateUtils.getTime());
        updateOrder.setUpdateTime(DateUtils.getNowDate());
        updateOrder.setUpdateBy(SecurityUtils.getUsername());
        
        return orderMapper.updateOrder(updateOrder);
    }
    
    /**
     * 评价订单
     * 
     * @param orderId 订单ID
     * @param rating 评分(1-5)
     * @param comment 评价内容
     * @return 结果
     */
    @Override
    @Transactional
    public int reviewOrder(Long orderId, Integer rating, String comment) {
        // 查询订单
        Order order = orderMapper.selectOrderById(orderId);
        if (order == null) {
            return 0;
        }
        
        // 判断订单状态是否可评价（只有已完成状态可评价）
        if (!"3".equals(order.getStatus())) {
            return 0;
        }
        
        // 更新订单评价信息
        Order updateOrder = new Order();
        updateOrder.setOrderId(orderId);
        updateOrder.setRating(rating);
        updateOrder.setComment(comment);
        updateOrder.setReviewTime(DateUtils.getTime());
        updateOrder.setUpdateTime(DateUtils.getNowDate());
        updateOrder.setUpdateBy(SecurityUtils.getUsername());
        
        return orderMapper.updateOrder(updateOrder);
    }
    
    /**
     * 删除订单（仅限已完成或已取消的订单）
     * 
     * @param orderId 订单ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteOrder(Long orderId) {
        // 查询订单
        Order order = orderMapper.selectOrderById(orderId);
        if (order == null) {
            return 0;
        }
        
        // 判断订单状态是否可删除（只有已完成或已取消的订单可删除）
        if (!"3".equals(order.getStatus()) && !"4".equals(order.getStatus())) {
            return 0;
        }
        
        // 逻辑删除订单及明细
        Order updateOrder = new Order();
        updateOrder.setOrderId(orderId);
        updateOrder.setDelFlag("2"); // 已删除
        updateOrder.setUpdateTime(DateUtils.getNowDate());
        updateOrder.setUpdateBy(SecurityUtils.getUsername());
        
        return orderMapper.updateOrder(updateOrder);
    }
    
    /**
     * 再次购买
     * 
     * @param orderId 原订单ID
     * @return 新订单
     */
    @Override
    @Transactional
    public Order rebuyOrder(Long orderId) {
        // 查询原订单
        Order oldOrder = orderMapper.selectOrderById(orderId);
        if (oldOrder == null) {
            return null;
        }
        
        // 查询原订单明细
        List<OrderItem> oldItems = orderItemMapper.selectOrderItemsByOrderId(orderId);
        if (oldItems == null || oldItems.isEmpty()) {
            return null;
        }
        
        // 创建新订单
        Order newOrder = new Order();
        newOrder.setOpenid(oldOrder.getOpenid());
        newOrder.setTotalAmount(oldOrder.getTotalAmount());
        newOrder.setPayAmount(oldOrder.getPayAmount());
        newOrder.setPayType(oldOrder.getPayType());
        newOrder.setStatus("0"); // 待付款
        newOrder.setReceiverName(oldOrder.getReceiverName());
        newOrder.setReceiverPhone(oldOrder.getReceiverPhone());
        newOrder.setReceiverAddress(oldOrder.getReceiverAddress());
        newOrder.setAddressId(oldOrder.getAddressId());
        
        // 生成订单号
        String orderNo = generateOrderNo();
        newOrder.setOrderNo(orderNo);
        
        // 设置创建时间
        newOrder.setCreateTime(DateUtils.getNowDate());
        newOrder.setCreateBy(SecurityUtils.getUsername());
        newOrder.setDelFlag("0");
        
        // 插入新订单
        orderMapper.insertOrder(newOrder);
        
        // 复制原订单明细到新订单
        for (OrderItem oldItem : oldItems) {
            OrderItem newItem = new OrderItem();
            newItem.setOrderId(newOrder.getOrderId());
            newItem.setProductId(oldItem.getProductId());
            newItem.setProductName(oldItem.getProductName());
            newItem.setProductImage(oldItem.getProductImage());
            newItem.setProductPrice(oldItem.getProductPrice());
            newItem.setQuantity(oldItem.getQuantity());
            newItem.setTotalPrice(oldItem.getTotalPrice());
            newItem.setCreateTime(DateUtils.getNowDate());
            newItem.setCreateBy(SecurityUtils.getUsername());
            newItem.setDelFlag("0");
            
            orderItemMapper.insertOrderItem(newItem);
        }
        
        return newOrder;
    }
    
    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        // 生成格式：yyyyMMddHHmmssSSS + 4位随机数
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String dateStr = sdf.format(new Date());
        
        // 4位随机数
        Random random = new Random();
        int randomNum = random.nextInt(10000);
        String randomStr = String.format("%04d", randomNum);
        
        return dateStr + randomStr;
    }
} 